<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
//redis任务队列
class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;
    /**
     * Create a new job instance.
     */
    public function __construct($podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * Execute the job.
     */


    public function handle()
    {
        // 使用原子锁确保同一时间只能有一个进程更新特定用户的积分
        $lockName = "lockmissiondispatch";
        $lock = Cache::lock($lockName, 600); // 锁的有效期为10分钟

        if ($lock->get()) {
            try {
                //Log::info("模拟耗时操作开始...");
                //sleep(10);
                for($i=0;$i<100;$i++){
                    DB::table('test')->insert($this->podcast);
                }
                //Log::info("模拟耗时操作结束。");
                //Log::info("更新完成。");
            } finally {
                // 确保无论是否发生异常都释放锁
                $lock->release();
            }
        } else {
            // 如果无法获取锁，则可能是另一个进程已经在处理这个任务
            //Log::info("另一个进程已经在处理这个任务");
        }
    }
}
